//
//  ICJSBridgeWebViewController.m
//  ICome
//
//  Created by zhang_rongwu on 16/3/4.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICWebViewController.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "ICReceiveShareObject.h"
#import "ICShareViewController.h"
#import "ICShareInstance.h"
#import "NSDictionary+URL.h"
#import "ICWebViewController+JSCallBack.h"
#import "ICPullComboBoxView.h"
#import "ICCommonGroup.h"
#import "ICEmptyStyleView.h"

#import "ICActionSheetView.h"
#import "ICNavigationController.h"
#import "ICMessageForwardController.h"



@interface ICWebViewController()<WKNavigationDelegate, WKUIDelegate, JSBridgeManagerDelegate, ICShareDelegate, ICPullComboBoxDelegate,ICActionSheetViewDelegate>

@property (nonatomic, strong)NSString *path;
@property (nonatomic , strong)ICPullComboBoxView * boxView;
@property (nonatomic, strong)ICEmptyStyleView *emptyView;
@property (nonatomic, strong) UIButton *remindButton;
@property (nonatomic, strong) UIButton *searchButton;



@end

@implementation ICWebViewController

+(ICWebViewController *)jsBridgeWKWebViewWithPath:(NSString *)path title:(NSString *)title {
    ICWebViewController *viewController = [[ICWebViewController alloc] init];
    viewController.path = path;
    
    viewController.title = @"加载中...";
    
    return viewController;
}

-(instancetype)init {
    if (self = [super init]) {
        //        [ICTools removeAllCachedResponses];
        self.isHideNavigationBar = NO;
        //        self.fd_interactivePopDisabled = YES;
        [self setWebViewUserAgent];
        self.extendedLayoutIncludesOpaqueBars = NO;

//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(begainFullScreen) name:UIWindowDidBecomeVisibleNotification object:nil];//进入全屏
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil];//退出全屏
    }
    return self;
}

-(void)wxonResp:(NSNotification *)notification
{
    NSLog(@"notification = %@,%@",notification.name,notification.userInfo);
    NSDictionary * dict =notification.userInfo;
    
    
    NSDictionary *args;
    if([dict[@"errCode"] intValue] == -2){
        args = @{@"success":@false,
                 @"data":@{@"no":@1,
                           @"msg":@"分享取消"}};
    }else if([dict[@"errCode"] intValue] !=0 ){
        args = @{@"success":@false,
                 @"data":@{@"no":@2,
                           @"msg":@"分享失败"}};
    }else if([dict[@"errCode"] intValue] ==0)
    {
        args = @{@"success":@true,
                 @"data":@{@"no":@0,
                           @"msg":@"分享成功"}};
    }
    
    
    [self.jsBridge postNotificationJavaScript:[self returnResult:self.callbackMap[@"system.shareToWechat"] args:args] toWebView:self.webView];
}


- (void)setWebViewUserAgent {
    WEAKSELF
    [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError * _Nullable error) {
        NSString *userAgent = result;
        NSString *newUserAgent = [userAgent stringByAppendingString:[ICJSBridgeTools getOS]];
        
        if (SystemVersion < 9.0) {
            NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
            [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
        } else {
            weakSelf.webView.customUserAgent = newUserAgent;
        }
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.statusBarView.backgroundColor = NE_BACKGROUND_COLOR;
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    [self.view addSubview:self.webView];
    [self.webView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.statusBarView.mas_bottom); // web页面不是配iOS 特殊处理
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
    }];
    
    self.permURL = self.originalURL;
    
    self.configURL = [self getPermissionURL];  // 设置校验时需要用到的 url
    
    self.jsBridge = [JSBridgeManager jsBridgeWithDelegate:self];
    self.webView.navigationDelegate = self.jsBridge;
    self.webView.UIDelegate = self;
    
    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
    [self.progressView setTrackTintColor:[UIColor colorWithWhite:1.0f alpha:0.0f]];
    [self.progressView setFrame:CGRectMake(0, 64, App_Frame_Width, 2)];
    [self.progressView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
    
    //设置进度条颜色
    [self.progressView setTintColor:[UIColor colorWithRed:0.400 green:0.863 blue:0.133 alpha:1.000]];
    [self.view addSubview:self.progressView];
    
    [self loadWKWebView:self.webView];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self loadWKWebView:self.webView];
//    });
    [self setConfigNavigationBar];
}

- (void)setNav {
    
    //[self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"App_menubox_blue"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonClicked)]];
    //
    
    UIButton *informationCardBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [informationCardBtn addTarget:self action:@selector(rightBarButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [informationCardBtn setImage:[UIImage imageNamedFromiComeSDKBundle:@"App_menubox_blue"] forState:UIControlStateNormal];
    informationCardBtn.bounds = CGRectMake(0, 0, 33, 33);
    [informationCardBtn setImageEdgeInsets:UIEdgeInsetsMake(7, 7, 7, 7)];
    //    [informationCardBtn sizeToFit];
    UIBarButtonItem *informationCardItem = [[UIBarButtonItem alloc] initWithCustomView:informationCardBtn];
    
    
    //    UIBarButtonItem *fixedSpaceBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //    fixedSpaceBarButtonItem.width = 22;
    
    
    UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    settingBtn.bounds = CGRectMake(0, 0, 33, 33);
    [settingBtn setImageEdgeInsets:UIEdgeInsetsMake(7, 14, 7, 0)];
    [settingBtn addTarget:self action:@selector(didCloseWebView) forControlEvents:UIControlEventTouchUpInside];
    [settingBtn setImage:[UIImage imageNamedFromiComeSDKBundle:@"App_close_white"] forState:UIControlStateNormal];
    //    [settingBtn sizeToFit];
    UIBarButtonItem *settingBtnItem = [[UIBarButtonItem alloc] initWithCustomView:settingBtn];
    
    self.navigationItem.rightBarButtonItems  = @[informationCardItem,settingBtnItem];
    
    [self setLeftBarButtonItemsWithCloseItem:NO];
//    [self setRightBarButtonItemsWithCloseItem:NO];
}

- (void)setLeftBarButtonItemsWithCloseItem:(BOOL)close {
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamedFromiComeSDKBundle:@"App_back_blue"] forState:UIControlStateNormal];
    //    [backBtn sizeToFit];
    backBtn.bounds = CGRectMake(0, 0, 33, 33);
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(6.5, 0, 6.5, 22)];
    UIBarButtonItem *backBtnItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    
    
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn addTarget:self action:@selector(didCloseWebView) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setImage:[UIImage imageNamedFromiComeSDKBundle:@"App_close_white"] forState:UIControlStateNormal];
    [closeBtn sizeToFit];
    UIBarButtonItem *closeBtnItem = [[UIBarButtonItem alloc] initWithCustomView:closeBtn];
    if (close) {
        UIBarButtonItem *fixedSpaceBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        fixedSpaceBarButtonItem.width = 25;
        self.navigationItem.leftBarButtonItems = @[backBtnItem,fixedSpaceBarButtonItem,closeBtnItem];
    } else {
        self.navigationItem.leftBarButtonItems = @[backBtnItem];
    }
}

- (void)setRightBarButtonItemsWithCloseItem:(BOOL)close {
   
    if (close) {
        UIButton *informationCardBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [informationCardBtn addTarget:self action:@selector(rightBarButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        [informationCardBtn setImage:[UIImage imageNamedFromiComeSDKBundle:@"App_menubox_blue"] forState:UIControlStateNormal];
        informationCardBtn.bounds = CGRectMake(0, 0, 33, 33);
        [informationCardBtn setImageEdgeInsets:UIEdgeInsetsMake(7, 7, 7, 7)];
        UIBarButtonItem *informationCardItem = [[UIBarButtonItem alloc] initWithCustomView:informationCardBtn];
      
        UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        settingBtn.bounds = CGRectMake(0, 0, 33, 33);
        [settingBtn setImageEdgeInsets:UIEdgeInsetsMake(7, 14, 7, 0)];
        [settingBtn addTarget:self action:@selector(didCloseWebView) forControlEvents:UIControlEventTouchUpInside];
        [settingBtn setImage:[UIImage imageNamedFromiComeSDKBundle:@"App_close_white"] forState:UIControlStateNormal];
        UIBarButtonItem *settingBtnItem = [[UIBarButtonItem alloc] initWithCustomView:settingBtn];
        self.navigationItem.rightBarButtonItems  = @[informationCardItem,settingBtnItem];
    } else {
        UIButton *informationCardBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [informationCardBtn addTarget:self action:@selector(rightBarButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        [informationCardBtn setImage:[UIImage imageNamedFromiComeSDKBundle:@"App_menubox_blue"] forState:UIControlStateNormal];
        informationCardBtn.bounds = CGRectMake(0, 0, 33, 33);
        [informationCardBtn setImageEdgeInsets:UIEdgeInsetsMake(7, 7, 7, 7)];
        UIBarButtonItem *informationCardItem = [[UIBarButtonItem alloc] initWithCustomView:informationCardBtn];
        self.navigationItem.rightBarButtonItems  = @[informationCardItem];
    }
    [self setLeftBarButtonItemsWithCloseItem:NO];
}

- (void)setConfigNavigationBar {
    NSURL *url = [NSURL URLWithString:self.path];
    NSString *query = url.query;
    NSDictionary *configDict = nil;
    if (![ICTools stringEmpty:(query)]) {
        configDict = [NSDictionary dictionaryWithURLQuery:query];
    }
    if (![ICTools isObjEmpty:configDict]) {
        if ([configDict[@"toolbar"] isEqualToString:@"0"]) {
            [self hideNavigationBar];
        }
    }
}


- (NSString *)getPermissionURL {
    NSString *url = self.originalURL;
    if (![ICTools stringEmpty:self.originalURL]) {
        NSURL *req = [NSURL URLWithString:self.originalURL];
        NSString *path = req.path;
        if (![ICTools stringEmpty:path]) {
            url = @"";
            NSRange reqPathRang = [self.originalURL rangeOfString:path];
            url = [NSString stringWithFormat:@"%@", [self.originalURL substringToIndex:reqPathRang.location]];
        }
    }
    return url;
}

- (void)backClick {
    NSLog(@"backClick");
    if ([self.webView canGoBack]) {
        
        // 对工作流应用 onUnload 特殊处理 勿删除
        [self.webView resignFirstResponder];
        if ([[self.webView.URL absoluteString] hasPrefix:@"http://bpm.enn.cn"]) {
            [self.webView evaluateJavaScript:@"AWSFormMainUtil.onUnloadEvent()" completionHandler:^(NSString *message, NSError * _Nullable error) {
                NSLog(@"js回调信息 error ： %@", error);
            }];
            [self.webView evaluateJavaScript:@"document.activeElement.blur()" completionHandler:^(NSString *message, NSError * _Nullable error) {
                NSLog(@"js回调信息 error ： %@%@", message,error);
            }];
        }
//        document.activeElement.blur()
        
        [self.webView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)rightBarButtonClicked {
    [self.boxView viewTap];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNav];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxonResp:) name:@"wxonResp" object:nil];//wxonResp
    if (self.isHideNavigationBar) {
        [self.navigationController setNavigationBarHidden:YES animated:NO];
    }
   
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wxonResp" object:nil];
    self.navigationController.navigationBarHidden = NO;
    [self.boxView removeFromSuperview];
}

- (void)loadWKWebView:(WKWebView *)webView {
    NSString *url = [self.path stringByReplacingOccurrencesOfString:@" " withString:@""];
    //[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString encodeString:url]]]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
// KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webView) {
        [self.progressView setAlpha:1.0f];
        BOOL animated = self.webView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.webView.estimatedProgress animated:animated];
        if(self.webView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    } else if ([keyPath isEqualToString:@"title"]) {
        if (object == self.webView) {
            self.title = self.webView.title;
        }
    }
}

- (void)jsBridge:(JSBridgeManager *)bridge didReceivedNotiDict:(NSDictionary*)dict Notification:(NSString *)notificationString fromWebView:(WKWebView *)webview {
    [self executeJSBridge:notificationString];
}
- (void)executeJSBridge:(NSString *)url {
    NSArray *components = [url componentsSeparatedByString:@":"];
    if ([components count] >= 3) {
        //功能
        NSString *function = (NSString *)[components objectAtIndex:1];
        //回调方法ID
        int callbackId = [((NSString *)[components objectAtIndex:2])intValue];
        //参数
        NSString *argsAsString = [(NSString *)[components objectAtIndex:3] stringByReplacingPercentEscapesUsingEncoding : NSUTF8StringEncoding];
        NSDictionary *param = nil;
        if (argsAsString.length > 0) {
            param = [NSJSONSerialization JSONObjectWithData:[argsAsString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
        }
        [self handleCall:function callbackId:[NSString stringWithFormat:@"%d",callbackId] param:param];
    }
}

- (void)dealloc {
    // 移除观察者
    @try {
        [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
        [self.webView removeObserver:self forKeyPath:@"title"];
    }
    @catch (NSException *exception) {
    }
}

- (void)didCloseWebView {
    [self webViewDidClose:self.webView];
}

#pragma mark -- WKUIDelegate
- (void)webViewDidClose:(WKWebView *)webView {
    [self.navigationController popViewControllerAnimated:YES];
}

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    WKFrameInfo *frameInfo = navigationAction.targetFrame;
    if (![frameInfo isMainFrame]) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                        style:UIAlertActionStyleCancel
                                                      handler:^(UIAlertAction *action) {
                                                          completionHandler();
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          completionHandler(YES);
                                                      }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
                                                        style:UIAlertActionStyleCancel
                                                      handler:^(UIAlertAction *action){
                                                          completionHandler(NO);
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
    completionHandler(@"Client Not handler");
}

// 页面打开失败
- (void)jsBridge:(JSBridgeManager *)bridge didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    self.title = @"加载失败..";
    if (self.isHideNavigationBar) {
        [self showNavigationBar];
    }
    
    self.emptyView.hidden = NO;
    
    if (error.code == NSURLErrorCancelled)  {
        self.emptyView.hidden = YES;
        return;
    }
    if (error.code == 22) //The operation couldn’t be completed. Invalid argument // 操作无法完成 参数错误
    {
        [MBProgressHUD showError:@"操作无法完成，参数错误"];
    }
    else if (error.code == -1001) //The request timed out.  webview code -999的时候会收到－1001
    {
        [MBProgressHUD showError:@"请求超时"];
    }
    else if (error.code == -1005) //The network connection was lost.
    {
        [MBProgressHUD showError:@"连接失败"];
    }
    else if (error.code == -1009){ //The Internet connection appears to be offline
        {
            //do nothing
        }
    }
}

// 分享处理
- (BOOL)shareInfoToSession:(NSDictionary *)info {
    
    if (info[@"title"]&&info[@"summary"]&&info[@"imageURL"]&&info[@"shareType"]&&info[@"appName"]&&info[@"targetURL"]) {
        
        NSArray *imageInfo = [info[@"imageURL"] componentsSeparatedByString:@"base64,"];
        NSDictionary *queryDict = @{@"title":[NSString encodeString:info[@"title"]],
                                    @"desc":[NSString encodeString:info[@"summary"]],
                                    @"thumbData":[NSString encodeString:[imageInfo objectAtIndex:1]],
                                    @"shareType":info[@"shareType"],
                                    @"displayName":[NSString encodeString:info[@"appName"]],
                                    @"webpageUrl":[NSString encodeString:info[@"targetURL"]]};
        NSLog(@"%@", info[@"imageURL"]);
        if ([info[@"extOption"] intValue] == 1) { // 群组
            //            ICShareViewController *shareVc = [[ICShareViewController alloc] init];
            //            shareVc.delegate = self;
            //            shareVc.shareContent = @{@"shareObject":queryDict};
            //            ICNavigationController *nvc = [[ICNavigationController alloc] initWithRootViewController:shareVc];
            //            [self presentViewController:nvc animated:NO completion:nil];
            
            ICMessageForwardController *vc = [[ICMessageForwardController alloc] init];
            vc.shareContent = @{@"shareObject":queryDict};
            vc.name = @"分享";
            ICNavigationController *nvc = [[ICNavigationController alloc] initWithRootViewController:vc];
            [self presentViewController:nvc animated:NO completion:nil];
            
        } else { // 动态
           
        }
        
        return YES;
    }
    return NO;
}

#pragma ICShareDelegate
- (void)shareViewController:(ICShareViewController *)shareVc confirmForShareData:(ICShareInstance *)shareData {
    ICChatViewController *chatVc = [[ICChatViewController alloc] init];
    chatVc.group = shareData.group;
    chatVc.shareContent = shareData;
    [self.navigationController pushViewController:chatVc animated:NO];
    [shareVc dismissViewControllerAnimated:NO completion:nil];
}

#pragma ICPullComboBoxDelegate
- (void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *uString = [self.webView.URL absoluteString];
    if (uString == nil) {
        return;
    }
    switch (indexPath.row) {
        case 0: {
            if (![ICTools stringEmpty:uString]) {
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                pasteboard.string = uString;
                [MBProgressHUD showSuccess:@"复制成功"];
            } else {
                [MBProgressHUD showError:@"复制失败"];
            }
        }
            break;
        case 1: {
            NSURL *url = [[NSURL alloc] initWithString:uString];
            [[UIApplication sharedApplication] openURL:url];
        }
            break;
        default:
            break;
    }
}

-(UIView *)statusBarView {
    if (!_statusBarView) {
        _statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, 0)];
        [self.view addSubview:_statusBarView];
    }
    return _statusBarView;
}

-(NSMutableArray *)jsApiList {
    if (!_jsApiList) {
        _jsApiList = [[NSMutableArray alloc] init];
    }
    return _jsApiList;
}

-(NSMutableDictionary *)callbackMap {
    if (!_callbackMap) {
        _callbackMap = [[NSMutableDictionary alloc] init];
    }
    return _callbackMap;
}

-(NSMutableDictionary *)jsRequestParam {
    if (!_jsRequestParam) {
        _jsRequestParam = [[NSMutableDictionary alloc] init];
    }
    return  _jsRequestParam;
}

-(WKWebView *)webView {
    if (!_webView) {
        _webView = [[WKWebView alloc] init];
        if (@available(iOS 11.0, *)) {
            _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            _webView.scrollView.scrollIndicatorInsets = _webView.scrollView.contentInset;
        }
    }
    return _webView;
}

-(ICPullComboBoxView *)boxView {
    if (!_boxView) {
        ICComboxItem *copyLink = [ICComboxItem itemWithIcon:@"icon_web_fz" title:@"复制链接" destVcClass:nil parameter:nil];
        ICComboxItem *choiceBrowser = [ICComboxItem itemWithIcon:@"icon_web_safari" title:@"Safari打开" destVcClass:nil parameter:nil];
        ICCommonGroup *baseGroup = [[ICCommonGroup alloc] init];
        baseGroup.items = @[copyLink, choiceBrowser];
        
        _boxView = [[ICPullComboBoxView alloc] initWithFrame:CGRectMake(0, ([ICTools getStatusbarHeight] + [ICTools getNavbarHeight]), App_Frame_Width, APP_Frame_Height)];
        [_boxView.dataList addObject:baseGroup];
        [_boxView.tableView reloadData];
        _boxView.delegate = self;
        [self.view.window addSubview:_boxView];
    }
    return _boxView;
}

-(ICEmptyStyleView *)emptyView {
    if (!_emptyView) {
        _emptyView = [[ICEmptyStyleView alloc] initWithTitle:@"轻触屏幕重新加载" placeholderImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_webView_empty"] imageURL:@""];
        _emptyView.hidden = YES;
        _emptyView.frame = CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height);
        [self.view addSubview:_emptyView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            NSString *uString = [self.webView.URL absoluteString];
            if (uString == nil) {
                uString = self.path;
            }
            [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:uString]]];
            _emptyView.hidden = YES;
            self.title = @"加载中..";
        }];
        [_emptyView addGestureRecognizer:tap];
    }
    return _emptyView;
}

- (ICWebNavTitleView *)navTitleView {
    if (!_navTitleView) {
        _navTitleView = [[ICWebNavTitleView alloc] initWithFrame:CGRectMake(0, 0, 200, 45)];
    }
    return _navTitleView;
}


- (UIButton *)remindButton
{
    if (_remindButton == nil) {
        
        _remindButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _remindButton.frame = CGRectMake(0, 0, 22., 22.);
        [_remindButton setImageEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
        [_remindButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"calendar_close"] forState:UIControlStateNormal];
        //        [_remindButton addTarget:self action:@selector(remindBarButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _remindButton;
}

- (UIButton *)searchButton
{
    if (_searchButton == nil) {
        
        _searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _searchButton.frame = CGRectMake(0, 0, 22., 22.);
        [_searchButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"calendar_search"] forState:UIControlStateNormal];
        [_searchButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"calendar_search"] forState:UIControlStateHighlighted];
        [_searchButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        //        [_searchButton addTarget:self action:@selector(searchBarBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchButton;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    if (navigationType==UIWebViewNavigationTypeBackForward) {
        self.webView.canGoBack?[self.webView goBack]:[self.navigationController popViewControllerAnimated:YES];
    }
    return YES;
}

-(ICActionSheetView *)actionSheet {
    if (!_actionSheet) {
        _actionSheet = [[ICActionSheetView alloc] initWithTitles:@[@"文件",@"从相册选取"] delegate:self cancelButtonTitle:@"取消"];
    }
    return _actionSheet;
}

- (void)ActionSheetView:(ICActionSheetView *)actionSheetView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        ICDocumentViewController *docVC = [[ICDocumentViewController alloc] init];
        docVC.delegate = self;
        // ICNavigationController *nav = [[ICNavigationController alloc] initWithRootViewController:docVC];
        [self.navigationController pushViewController:docVC animated:YES];

    } else if (buttonIndex == 1) {
        [[ICPhotoPickerManager shareInstace] selectPhotoWithPickSourceType:2 maxCount:1 fromController:self completionBlock:^(NSMutableArray *imageArray) {
            if (imageArray.count == 0) {
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                // 上传服务器
                NSLog(@"imageArray = %@",imageArray);
                
                
//                NSString *url = [self appendRequestBaseURL:@"fileserver/image/sendImage"];
//                NSDictionary *parameters = @{@"fileName" : imgName};
//                [ICNetworkHelper uploadWithURL:url parameters:parameters data:imgData name:@"file" fileName:imgName mimeType:@"image/png" progress:^(NSProgress *progress) {
//
//                } success:^(id responseObject) {
//                    success(responseObject);
//                } failure:^(NSError *error) {
//                    failure(error);
//                }];
                NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
                NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
                NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
            
                UIImage * image = imageArray[0];
                NSString *fileName = [NSString stringWithFormat:@"IMG_%@%@",timeString,@".png"];
                NSData *imageData = UIImagePNGRepresentation(image);
                
                __block NSString *callBackName = self.callName;
                //@"device.uploadFile";
                NSString *trueName = [fileName originName];
                NSString *serverUrl = self.jsRequestParam[callBackName][@"serverUrl"];
                NSDictionary *parameters = @{@"fileName" : trueName};
                
                [ICNetworkHelper uploadWithURL:serverUrl parameters:parameters data:imageData name:@"file" fileName:trueName mimeType:@"image/png" progress:^(NSProgress *progress) {
                    NSLog(@"Progress is %f", progress.fractionCompleted);
                } success:^(id responseObject) {
                    NSLog(@"上传成功");
                    NSDictionary *args=@{@"success":@true,@"data":responseObject};
                    [self.jsBridge postNotificationJavaScript:[self returnResult:self.callbackMap[callBackName] args:args] toWebView:self.webView];
                    
                } failure:^(NSError *error) {
                    NSDictionary *args = @{@"success":@false,
                                           @"data":@{@"errno":@(error.code),
                                                     @"error":error.domain}};
                    [self.jsBridge postNotificationJavaScript:[self returnResult:self.callbackMap[callBackName] args:args] toWebView:self.webView];
                }];

            }
        }];

    }
}



@end



